package com.bms.clent.interceptor;

import com.bms.clent.pojo.KeYanRenYuan;
import com.bms.clent.service.impl.KeYanRenYuanServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;


import com.bms.clent.token.SkipJWT;
import com.bms.clent.util.JwtUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author thinknovo
 * @version 1.0
 * @description JwtAuthenticationInterceptor.java
 */
public class JwtAuthenticationInterceptor implements HandlerInterceptor {
    @Resource
    private KeYanRenYuanServiceImpl keYanRenYuanService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        // 从请求头中取出 token  这里需要和前端约定好把jwt放到请求头一个叫token的地方
        String token = httpServletRequest.getHeader("token");
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        //检查是否有SkipJWT注释，有则跳过认证
        if (method.isAnnotationPresent(SkipJWT.class)) {
            SkipJWT passToken = method.getAnnotation(SkipJWT.class);
            if (passToken.required()) {
                return true;
            }
        }
        //默认全部检查
        else {
            System.out.println("被jwt拦截需要验证  url=" + httpServletRequest.getRequestURL());
            // 执行认证
            if (token == null) {
                System.out.println("用户没有token，无法执行后续任务");
                httpServletResponse.setContentType("text/html;charset=utf-8");
                Map<String, Object> map = new HashMap<>();
                map.put("code", 500);
                map.put("msg", "用户未登录，无法使用此功能");

                httpServletResponse.getWriter().print(new ObjectMapper().writeValueAsString(map));
                return false;
            }

            // 获取 token 中的 username
            String userId = JwtUtils.getAudience(token);
            System.out.println("userId=" + userId);
            if(userId == null) {
                System.out.println("用户没有token，并且也没有获取用户的主键，无法执行后续任务");
                return false;
            }

            //找找看是否有这个user   因为我们需要检查用户是否存在
            KeYanRenYuan keYanRenYuan = keYanRenYuanService.selectById(Integer.parseInt(userId));

            if (keYanRenYuan == null) {
                System.out.println("用户没有token，并且也没有查询到对应的用户，无法执行后续任务");
                return false;
            }

            // 验证 token
            JwtUtils.verifyToken(token, userId);

            //获取载荷内容
            String userName = JwtUtils.getClaimByName(token, "userName").asString();
            String realName = JwtUtils.getClaimByName(token, "realName").asString();
            System.out.println("username=" + userName);
            System.out.println("realName=" + realName);

            //放入attribute以便后面调用
            httpServletRequest.setAttribute("userName", userName);
            httpServletRequest.setAttribute("realName", realName);


            return true;

        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }
}
